package com.steven.im.ui.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import com.steven.im.App;
import com.steven.im.R;
import com.steven.im.base.BaseActivity;
import com.steven.im.base.Constant;
import com.steven.im.entity.BaseEntity;
import com.steven.im.entity.LoginEntity;
import com.steven.im.net.MyCallback;
import com.steven.im.net.Task;
import com.steven.im.net.Url;
import com.steven.im.utils.SPUtils;
import com.steven.im.utils.SaveParameterUtils;
import com.steven.im.utils.ScreenUtil;
import com.steven.im.utils.TitleBuilder;
import com.steven.im.utils.ToastUtil;
import com.steven.im.widget.CountTimer;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;

/**
 * 注册
 */
public class RegisterActivity extends BaseActivity {
    private String phone;
    private String phoneCode;
    private boolean isGetCodeImg = true;//默认是刷新过图片验证码的
    private boolean isHide = true;//明文和密码
    private boolean isChecked = true;//是否已经同意 用户协议
    CountTimer countTimer;
    @BindView(R.id.iv_codeImg) //验证码图片
            ImageView iv_codeImg;
    @BindView(R.id.et_codeImg)//图片验证码
            EditText et_codeImg;
    @BindView(R.id.et_phoneCode)//手机验证码
            EditText et_phoneCode;
    @BindView(R.id.tv_getcode)//获取验证码
            TextView tvGetcode;
    @BindView(R.id.ed_referralCode)//推介人代码
            EditText ed_referralCode;
    @BindView(R.id.et_password)//账户密码
            EditText et_password;
    @BindView(R.id.iv_eye)//显示隐藏
            ImageView ivHideOr;
    @BindView(R.id.cb_protocol)
    ImageView cb_protocol;
    @BindView(R.id.tv_register)
    TextView tv_register;

    @Override
    public void setListen() {
        et_codeImg.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (et_codeImg.getText().toString().length() > 0) {
                    tv_register.setBackgroundResource(R.drawable.bg_btn);
                } else {
                    if (("").equals(et_phoneCode.getText().toString()) && ("").equals(et_password.getText().toString())) {
                        tv_register.setBackgroundResource(R.drawable.bg_btn_gray);
                    }
                }
            }
        });
        et_phoneCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (et_phoneCode.getText().toString().length() == 0) {
                    if (("").equals(et_password.getText().toString()) && ("").equals(et_codeImg.getText().toString())) {
                        tv_register.setBackgroundResource(R.drawable.bg_btn_gray);
                    }
                } else {
                    tv_register.setBackgroundResource(R.drawable.bg_btn);
                }
            }
        });
        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                et_password.setSelection(s.toString().length());
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (et_password.getText().toString().length() > 0) {
                    tv_register.setBackgroundResource(R.drawable.bg_btn);
                } else {
                    if (("").equals(et_phoneCode.getText().toString()) && ("").equals(et_codeImg.getText().toString())) {
                        tv_register.setBackgroundResource(R.drawable.bg_btn_gray);
                    }
                }
            }
        });
    }

    @Override
    public void setTitleBarColor() {

    }

    @Override
    public int intiLayout() {
        return R.layout.activity_register;
    }

    @Override
    public void initView() {
        new TitleBuilder(this).setTitleText("注册")
                .setLeftIcoListening(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                });

        countTimer = new CountTimer(tvGetcode);
    }

    @Override
    public void initData() {
        phone = getIntent().getStringExtra("phone");
        Picasso.with(App.getContext()).load(Url.BaseUrl + "/captcha/generateImage").memoryPolicy(MemoryPolicy.NO_CACHE).into(iv_codeImg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countTimer != null) {
            countTimer.cancel();
            tvGetcode.setEnabled(true);
            tvGetcode.setText("获取验证码");
        }
    }


    @OnClick({R.id.tv_getcode, R.id.tv_register, R.id.iv_codeImg, R.id.iv_eye, R.id.cb_protocol, R.id.tv_xieyi})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.tv_getcode://获取验证码
                if (!isGetCodeImg) {
                    refreshCodeImg();
                }
                if (!"".equals(et_codeImg.getText().toString())) {
                    sendVerify();
                } else {
                    ToastUtil.showShort(App.getContext(), "请输入图片验证码！");
                }
                break;

            case R.id.iv_eye://密码显示隐藏
                if (!isHide) {
                    //隐藏
                    ivHideOr.setImageResource(R.drawable.login_eyehide);
                    et_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {
                    //显示
                    ivHideOr.setImageResource(R.drawable.login_eye);
                    et_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
                isHide = !isHide;
                break;
            case R.id.iv_codeImg://刷新验证码图片
                refreshCodeImg();
                break;
            case R.id.cb_protocol://是否已经阅读用户协议
                if (isChecked) {//没有
                    cb_protocol.setImageResource(R.drawable.login_agree);
                } else {
                    cb_protocol.setImageResource(R.drawable.login_agree01);
                }
                isChecked = !isChecked;
                break;
            case R.id.tv_register://注册
                //得判断
                if (("").equals(et_codeImg.getText().toString())) {
                    ToastUtil.showShort(App.getContext(), "请输入图片验证码！");
                } else if (("").equals(et_phoneCode.getText().toString())) {
                    ToastUtil.showShort(App.getContext(), "请输入手机验证码！");
                } else if (("").equals(et_password.getText().toString())) {
                    ToastUtil.showShort(App.getContext(), "请设置你的账户密码！");
                } else if (!isChecked) {
                    ToastUtil.showShort(App.getContext(), "请先阅读用户协议！");
                } else {
                    register();
                }
                break;
            case R.id.tv_xieyi:
                startActivity(new Intent(RegisterActivity.this, WebActivity.class).putExtra("title", "注册协议").putExtra("url", Url.REGISTER_AGREEMENT));
                break;
        }
    }

    //刷新图片验证码
    private void refreshCodeImg() {
        isGetCodeImg = true;
        et_codeImg.setText("");
        Picasso.with(App.getContext()).load(Url.BaseUrl + "/captcha/generateImage").memoryPolicy(MemoryPolicy.NO_CACHE).into(iv_codeImg);
    }

    //用户注册
    private void register() {
        String mobileCode = et_phoneCode.getText().toString();
        final String password = et_password.getText().toString();
        String signCode = ed_referralCode.getText().toString();
        Task.getApiService().accountSign(mobileCode, phone, password, signCode).enqueue(new MyCallback<BaseEntity>(RegisterActivity.this) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                try {
                    if ("0".equals(response.body().getCode())) {
                        toLogin(password);
                    } else {
                        ToastUtil.showShort(RegisterActivity.this, response.body().getMessage());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {
                ToastUtil.showShort(App.getContext(), "注册失败！");
            }
        });
    }

    /**
     * 登录
     */
    private void toLogin(String pwd) {
        String token = SPUtils.get(getApplicationContext(), Constant.CommonInfo.TOKEN, "").toString();
        Task.getApiService().accountLogin(token, phone, pwd).enqueue(new MyCallback<LoginEntity>(RegisterActivity.this) {
            @Override
            protected void onSuccess(Response<LoginEntity> response) {
                try {
                    if ("0".equals(response.body().getCode()) && ("true").equals(response.body().getResult().getSuccess())) {//登录成功
                        //保存session信息
                        SaveParameterUtils.saveJseSessionId(response.body().getResult().getSessionId());
                        finish();
                    } else if ("1".equals(response.body().getCode())) {//用户不存在，先注册
                        ToastUtil.showShort(App.getContext(), response.body().getMessage());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {
                t.printStackTrace();
            }
        });
    }

    /**
     * 获取验证码
     */
    private void sendVerify() {
        countTimer.start();
        isGetCodeImg = false;
        Task.getApiService().sendPhoneCode(phone, et_codeImg.getText().toString()).enqueue(new MyCallback<BaseEntity>(RegisterActivity.this) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                if ("0".equals(response.body().getCode())) {
                    ToastUtil.showShort(App.getContext(), response.body().getMessage());
                }
            }

            @Override
            protected void onFailure(Throwable t) {
                ToastUtil.showShort(App.getContext(), "发送失败！");
            }
        });
    }
}
